import { ElMessage } from 'element-plus';
import axios from 'axios';
import _ from 'lodash-es';
import { clearToken, getToken, setToken } from '@/utils/auth';

// 访问前缀（线下）
export const BASE_NAME = import.meta.env.VITE_BASE_NAME_API;
export const BASE_MATTER_MAP_URL = 'https://www.xazrhh.com:1443/matterServerAlpha/#/login';
export const BASE_NAME_MAP = '/st_server_api_v2';
export const BASE_GEOSERVER_URL = 'https://www.xazrhh.com:1443';
// 响应码
export const ResponseSuccessCode = '00000';
export const ResponseCode = [
  {
    code: '00000',
    msg: '操作成功',
  },
  {
    code: 'A0001',
    msg: '未认证',
  },
  {
    cole: 'A0002',
    msg: '无权限',
  },
  {
    code: 'A0003',
    msg: '无效token',
  },
  {
    code: 'A0005',
    msg: '用户名不存在',
  },
  {
    code: 'A0004',
    msg: '刷新token与认证token不匹配',
  },
  {
    code: 'A0007',
    msg: '密码错误次数过多,请5分钟后再试',
  },
  {
    code: 'A0006',
    msg: '密码不正确',
  },
  {
    code: 'A1001',
    msg: '用户名已存在',
  },
  {
    code: 'A0101',
    msg: '参数错误',
  },
  {
    code: 'A1003',
    msg: '用户不存在',
  },
  {
    code: 'A1002',
    msg: '手机号已存在',
  },
  {
    code: 'A1101',
    msg: '角色不存在',
  },
  {
    code: 'A1102',
    msg: '存在用户绑定了角色，无法删除',
  },
  {
    code: 'A1202',
    msg: '',
  },
  {
    code: 'A1201',
    msg: '权限不存在',
  },
  {
    code: 'A1004',
    msg: '原密码不正确',
  },
  {
    code: 'A1302',
    msg: '组织不为空，无法删除',
  },
];

const http = axios.create({
  // timeout: 5000,
});

// 文件上传头
export const getFileHeaders = () => {
  return {
    Authorization: getToken() ? `Bearer ${getToken()}` : '',
    'CUSTOMIZE-CLIENT-TYPE': 'web',
  };
};

let isExpire = false;

/**
 *无感刷新Token方法
 *
 */
function refreshFn(tokenInfo) {
  const { expireTime, accessToken, refreshToken } = JSON.parse(tokenInfo);
  const remainTime = 10 * 60 * 1000;

  if (expireTime - remainTime < Date.now() && expireTime > Date.now()) {
    if (!isExpire) {
      isExpire = true;
      axios
        .post(`${BASE_NAME}/api/auth/refresh`, { accessToken, refreshToken })
        .then((res) => {
          const { data } = res.data;

          localStorage.setItem(
            'tokenInfo',
            JSON.stringify({
              ...data,
              expireTime: Date.now() + data.expireIn,
            }),
          );
          setToken(data.accessToken, true);
        })
        .finally(() => {
          isExpire = false;
        });
    }
  }
}

// 请求拦截器
http.interceptors.request.use(
  (config) => {
    // 接口带token
    config.headers.Authorization = getToken() ? `Bearer ${getToken()}` : '';

    let tokenInfo = localStorage.getItem('tokenInfo');

    if (tokenInfo) {
      refreshFn(tokenInfo);
    }

    return config;
  },
  (error) => Promise.reject(error),
);

//  响应拦截器
http.interceptors.response.use(
  (response) => {
    // console.log(response, 'response');

    if (response?.data?.msg === '请求过于频繁，请稍后再试') {
      console.error(response.data.msg);
    }

    if (response.headers['content-type'] == 'application/json') {
      return response.data;
    }

    return response;
  },
  (error) => {
    if (error.response?.status == 500) {
      ElMessage.error('服务器内部错误');

      return;
    }

    if (error.response?.status == 404) {
      ElMessage.error('接口地址错误');

      return;
    }

    const responseError = _.find(ResponseCode, (item) => {
      if (item.code === error?.response?.data?.code) {
        return item;
      }
    });

    if (responseError) {
      if (['A0002', 'A0001', 'A0003'].includes(responseError.code)) {
        clearToken();
        ElMessage.error(error.response.data.message);
        location.assign('/#/login');
        setTimeout(() => {
          location.reload();
        }, 1000);
      } else {
        if (error.response.data.message) {
          ElMessage.error(error.response.data.message);
        }
      }
    }

    return Promise.reject(error?.response?.data || error);
  },
);

export default http;
